package cn.hl.hm.util.chinapay;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.chinapay.secss.SecssUtil;
/**
 * @author chao.sheng
 */
public class MPOrderServlet extends BaseServlet {
	/** 编号. */
	private static final long serialVersionUID = 1L;
	/** 日志. */
	private static Logger logger = Logger.getLogger(MPOrderServlet.class);

	/**
	 * 报文处理.
	 * @param request 请求
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@Override
	protected void processAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 解析参数
		Enumeration<String> names = request.getParameterNames();
		Map<String, String> params = new HashMap<String, String>();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String value = request.getParameter(name);
			if (value == null) {
				continue;
			} else {
				try {
					value = new String(value.getBytes("UTF-8"), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					logger.error(e.getMessage(), e);
				}
			}
			// 设置参数
			params.put(name, value);
		}
		String version=params.get("version");
		String busiType=params.get("busiType");
		String merId=params.get("merId");
		String merBgUrl=params.get("merBgUrl");
		String remoteAddr=params.get("remoteAddr");
		String merOrderNo=params.get("merOrderNo");
		String orderAmt=params.get("orderAmt");
		String tranDate=params.get("tranDate");
		String tranTime=params.get("tranTime");
		String accessType=params.get("accessType");
		String instuId=params.get("instuId");
		String acqCode=params.get("acqCode");
		String tranType=params.get("tranType");
		String curryNo=params.get("curryNo");
		String splitType=params.get("splitType");
		String splitMethod=params.get("splitMethod");
		String merSplitMsg=params.get("merSplitMsg");
		String bankInstNo=params.get("bankInstNo");
		String merPageUrl=params.get("merPageUrl");
		String commodityMsg=params.get("commodityMsg");
		String merResv=params.get("merResv");
		String tranReserved=params.get("tranReserved");
		String cardTranData=params.get("cardTranData");
		String payTimeOut=params.get("payTimeOut");
		String timeStamp=params.get("timeStamp");
		String riskData=params.get("riskData");
		
		/*
		 * tranReserved如果没有特殊字符，也可以不进行base64编码，相应的,APP就不需要base64编码.
		 */
		logger.debug("base64解密后tranReserved=["+tranReserved+"]");
		tranReserved = new String(Base64.decode(tranReserved.toCharArray()), "UTF-8");
		logger.debug("base64解密后tranReserved=["+tranReserved+"]");
		
		// 初始化
		SecssUtil secssUtil = new SecssUtil();
		String fileKey = merId;
		logger.debug("配置文件路径:"
				+ PathUtil.getValue("security_" + fileKey + "_url"));
				//命名标准：security_000000000000001.properties对应security_000000000000001_url
		secssUtil.init(PathUtil.getValue("security_" + fileKey + "_url"));
		logger.debug("商户号：" + merId + "，要加密的内容：" + riskData);
		secssUtil.encryptData(riskData);
		logger.debug("接收到的"+riskData);
		String encResult = secssUtil.getEncValue();
		logger.debug("CP公钥RSA加密后" + encResult);
		
		Map<String, String> map = new HashMap<String,String>();
		map.put("Version",version);
		map.put("BusiType",busiType);
		map.put("MerId",merId);
		map.put("MerBgUrl",merBgUrl);
		map.put("RemoteAddr",remoteAddr);
		map.put("MerOrderNo",merOrderNo);
		map.put("OrderAmt",orderAmt);
		map.put("TranDate",tranDate);
		map.put("TranTime",tranTime);
		map.put("AccessType",accessType);
		map.put("InstuId",instuId);
		map.put("AcqCode",acqCode);
		map.put("TranType",tranType);
		map.put("CurryNo",curryNo);
		map.put("SplitType",splitType);
		map.put("SplitMethod",splitMethod);
		map.put("MerSplitMsg",merSplitMsg);
		map.put("BankInstNo",bankInstNo);
		map.put("MerPageUrl",merPageUrl);
		map.put("CommodityMsg",commodityMsg);
		map.put("MerResv",merResv);
		map.put("TranReserved",tranReserved);
		map.put("CardTranData",cardTranData);
		map.put("PayTimeOut",payTimeOut);
		map.put("TimeStamp",timeStamp);
		map.put("RiskData",encResult);
		//商户签名
		secssUtil.sign(map);
		String signature = secssUtil.getSign();
		logger.debug("signature-->"+signature);
		
		Map<String, String> sendMap = new HashMap<String,String>();
		sendMap.put("riskData", encResult);
		sendMap.put("signature", signature);
		String sendmsg = getURLParam(sendMap, true, null);
		response.getWriter().write(sendmsg);
	}
	
	/**
	 * 转换成url参数
	 * @param map
	 * @param isSort 是否排序
	 * @param removeKey 不包含的key元素集
	 * @return
	 */
	public String getURLParam(Map map, boolean isSort, Set removeKey) {
		StringBuffer param = new StringBuffer();
		List msgList = new ArrayList();
		for (Iterator it = map.keySet().iterator(); it.hasNext();) {
			String key = (String) it.next();
			String value = (String) map.get(key);
			if (removeKey != null && removeKey.contains(key)) {
				continue;
			}
			msgList.add(key + "=" + value);
		}
		if (isSort) {
			// 排序
			Collections.sort(msgList);
		}
		for (int i = 0; i < msgList.size(); i++) {
			String msg = (String) msgList.get(i);
			if (i > 0) {
				param.append("&");
			}
			param.append(msg);
		}
		return param.toString();
	}
}
